package com.weijing.pretty_app.activity

import android.animation.ValueAnimator
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.LiveEventBus
import com.weijing.pretty_app.R
import com.weijing.pretty_app.databinding.ActivityHomeBinding
import com.weijing.pretty_app.fragment.UserModel
import com.weijing.pretty_app.models.SelectModel
import com.weijing.pretty_app.util.BluetoothSocketManager
import com.weijing.pretty_app.util.CoreUtil
import com.weijing.pretty_app.util.HalfCircleSeekBar
import com.weijing.pretty_app.util.HexConverter
import com.weijing.pretty_app.util.HexDataParse
import com.weijing.pretty_app.util.KeyUtil
import com.weijing.pretty_app.util.SPUtil
import com.weijing.pretty_app.util.ToastUtils
import com.weijing.pretty_app.util.UserRepository
import com.weijing.pretty_app.util.WorkTimerController
import java.util.Locale

private const val TAG = "HomeActivity"

/**
 * 主界面
 */
class HomeActivity : BaseActivity() {

    private val binding by lazy { ActivityHomeBinding.inflate(layoutInflater) }
    override fun getMainView(): View = binding.main

    private var leftUserModel: UserModel? = null
    private var rightUserModel: UserModel? = null
    private var seekBarMax1L = 100
    private var seekBarMin1L = 0
    private var seekBarMax2L = 100
    private var seekBarMin2L = 0
    private var seekBarMax3L = 10
    private var seekBarMin3L = 1
    private var seekBarMax1R = 100
    private var seekBarMin1R = 0
    private var seekBarMax2R = 100
    private var seekBarMin2R = 0
    private var seekBarMax3R = 10
    private var seekBarMin3R = 1

    // 用于保存每个容器对应的呼吸动画，便于后续取消动画
    private val breathingAnimators = mutableMapOf<View, ValueAnimator>()
    private val controllers = mutableMapOf<String, WorkTimerController>()
    private var actionFlagL = 0 //待机 0 ，准备1，输出2
    private var actionFlagR = 0 //待机 0 ，准备1，输出2
    private var receiveFlagL = 0 //接收待机状态 01/02/03(待机/准备/输出)
    private var receiveFlagR = 0 //接收待机状态 01/02/03(待机/准备/输出)
    private var mWorkCountL = 0 //计时器计算的手柄运行次数
    private var mWorkCountR = 0 //计时器计算的手柄运行次数

    private val dataListener: (data: ByteArray) -> Unit = { data ->
        val receivedText = HexConverter.byteArrayToHexString(data) // 默认是 ASCII 格式
        Log.d(TAG, "收到蓝牙数据: $receivedText")
        HexDataParse.parseHexString(receivedText) { funcCode, hexData ->
            Log.i(TAG, "接收到的转化数据-- $hexData")
            when (funcCode) {
                KeyUtil.E7 -> {   //最大值和最小值
                    Log.i(TAG, "功能码 E7 数据：$hexData")
                    if (hexData.size == 3) {
                        val fangXiang = HexDataParse.dataToUInt(listOf(hexData[0]))
                        when (fangXiang) {
                            1 -> {
                                val index = HexDataParse.dataToUInt(listOf(hexData[1]))
                                when (index) { //1-Intensity ,2-Duration, 3-HZ
                                    1 -> {
                                        val num = HexDataParse.dataToUInt(listOf(hexData[2]))
                                        setSeekbarValue(
                                            binding.homeSeekBar1l, binding.homeTv1l, num
                                        )
                                        Log.i(TAG, "IntensityL-- ${num}")
                                    }

                                    2 -> {
                                        val num = HexDataParse.dataToUInt(listOf(hexData[2]))
                                        setSeekbarValue(
                                            binding.homeSeekBar2l, binding.homeTv2l, num
                                        )
                                        Log.i(TAG, "DurationL-- ${num}")
                                    }

                                    3 -> {
                                        val num = HexDataParse.dataToUInt(listOf(hexData[2]))
                                        setSeekbarValue(
                                            binding.homeSeekBar3l, binding.homeTv3l, num
                                        )
                                        Log.i(TAG, "HZL-- ${num}")
                                    }
                                }
                            }

                            2 -> {
                                val index = HexDataParse.dataToUInt(listOf(hexData[1]))
                                when (index) { //1-Intensity ,2-Duration, 3-HZ
                                    1 -> {
                                        val num = HexDataParse.dataToUInt(listOf(hexData[2]))
                                        setSeekbarValue(
                                            binding.homeSeekBar1R, binding.homeTv1R, num
                                        )
                                        Log.i(TAG, "IntensityR-- ${num}")
                                    }

                                    2 -> {
                                        val num = HexDataParse.dataToUInt(listOf(hexData[2]))
                                        setSeekbarValue(
                                            binding.homeSeekBar2R, binding.homeTv2R, num
                                        )
                                        Log.i(TAG, "DurationR-- ${num}")
                                    }

                                    3 -> {
                                        val num = HexDataParse.dataToUInt(listOf(hexData[2]))
                                        setSeekbarValue(
                                            binding.homeSeekBar3R, binding.homeTv3R, num
                                        )
                                        Log.i(TAG, "HZR-- ${num}")
                                    }
                                }
                            }
                        }
                        Log.i(TAG, "fangxiang: $fangXiang")
                    }
                }

                KeyUtil.E9 -> { //指令9；01-待机、02-准备、03-输出
                    if (hexData.size == 2) {
                        val fangXiang = hexData[0]
                        val status = hexData[1] //状态
                        when (fangXiang) {
                            "01" -> {//左边  02-右边
                                when (status) { // 01/02/03(待机/准备/输出)
                                    "01" -> {
                                        runOnUiThread {
                                            setupPlayButton(
                                                binding.homeClActionL, binding.homeIvActionL, 1, "L"
                                            )
                                            receiveFlagL = 1
                                        }
                                    }

                                    "02" -> {
                                        runOnUiThread {
                                            setupPlayButton(
                                                binding.homeClActionL, binding.homeIvActionL, 2, "L"
                                            )
                                        }
                                    }

                                    "03" -> {
                                        runOnUiThread {
                                            setupPlayButton(
                                                binding.homeClActionL, binding.homeIvActionL, 3, "L"
                                            )
                                            receiveFlagL = 3
                                        }
                                    }
                                }
                            }

                            "02" -> {
                                when (status) { // 01/02/03(待机/准备/输出)
                                    "01" -> {
                                        runOnUiThread {
                                            setupPlayButton(
                                                binding.homeClActionR, binding.homeIvActionR, 1, "R"
                                            )
                                            receiveFlagR = 1
                                        }
                                    }

                                    "02" -> {
                                        runOnUiThread {
                                            setupPlayButton(
                                                binding.homeClActionR, binding.homeIvActionR, 2, "R"
                                            )
//                                            receiveFlagR = 2
                                        }
                                    }

                                    "03" -> {
                                        runOnUiThread {
                                            setupPlayButton(
                                                binding.homeClActionR, binding.homeIvActionR, 3, "R"
                                            )
                                            receiveFlagR = 3
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                KeyUtil.F2 -> { //指令17：获取最大值最小值 (AA FF F2 05(长度) 01(方向) 05 8C(能量密度) 05 64(脉宽) EE)
                    if (hexData.size == 5) {
                        val fangXiang = HexDataParse.dataToUInt(listOf(hexData[0]))
                        when (fangXiang) {
                            1 -> {  //1左边 2右边
                                runOnUiThread {
                                    val minIntensity = HexDataParse.dataToUInt(listOf(hexData[1]))
                                    val maxIntensity = HexDataParse.dataToUInt(listOf(hexData[2]))
                                    val mineDuration = HexDataParse.dataToUInt(listOf(hexData[3]))
                                    val maxDuration = HexDataParse.dataToUInt(listOf(hexData[4]))
                                    seekBarMax1L = maxIntensity
                                    seekBarMin1L = minIntensity
                                    binding.homeSeekBar1l.setMin(minIntensity)
                                    binding.homeSeekBar1l.setMax(maxIntensity)
                                    seekBarMax2L = maxDuration
                                    seekBarMin2L = mineDuration
                                    binding.homeSeekBar2l.setMin(mineDuration)
                                    binding.homeSeekBar2l.setMax(maxDuration)
                                    Log.i(
                                        TAG,
                                        "左侧: ${minIntensity}--${maxIntensity}---${mineDuration}--${maxIntensity}"
                                    )
                                    initJianL()
                                    initJiaL()
                                }
                            }

                            2 -> {
                                runOnUiThread {
                                    val minIntensity = HexDataParse.dataToUInt(listOf(hexData[1]))
                                    val maxIntensity = HexDataParse.dataToUInt(listOf(hexData[2]))
                                    val mineDuration = HexDataParse.dataToUInt(listOf(hexData[3]))
                                    val maxDuration = HexDataParse.dataToUInt(listOf(hexData[4]))

                                    seekBarMax1R = maxIntensity
                                    seekBarMin1R = minIntensity
                                    binding.homeSeekBar1R.setMin(minIntensity)
                                    binding.homeSeekBar1R.setMax(maxIntensity)
                                    seekBarMax2R = maxDuration
                                    seekBarMin2R = mineDuration
                                    binding.homeSeekBar2R.setMin(mineDuration)
                                    binding.homeSeekBar2R.setMax(maxDuration)

                                    initJianR()
                                    initJiaR()
                                }
                            }
                        }
                    }
                }

                KeyUtil.EC -> { //指令12 接收4个报警参数，使用在工作页面最底部
                    if (hexData.size == 3) {
                        val fangXiang = HexDataParse.dataToUInt(listOf(hexData[0]))
                        when (fangXiang) {
                            1 -> {  //1左边 2右边
                                //01/02/03/04/05【水温 手柄头温度 水流量 水位】
                                val index = HexDataParse.dataToUInt(listOf(hexData[1]))
                                //01-开启 00-关闭
                                val flag = HexDataParse.dataToUInt(listOf(hexData[2]))
                                when (flag) {
                                    0 -> {
                                        when (index) {
                                            1 -> {
                                                binding.homeClWenDuL1.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_00c1cd
                                                    )
                                                binding.homeTvWenDuL1.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_00C1CD
                                                    )
                                                )
                                            }

                                            2 -> {
                                                binding.homeClWenDuL2.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_00c1cd
                                                    )
                                                binding.homeTvWenDuL2.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_00C1CD
                                                    )
                                                )
                                            }

                                            3 -> {
                                                binding.homeClWenDuL3.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_00c1cd
                                                    )
                                                binding.homeTvWenDuL3.setTextColor(
                                                    ContextCompat.getColor(
                                                        this,
                                                        R.color.color_00C1CD
                                                    )
                                                )
                                            }

                                            4 -> {
                                                binding.homeIvShuiWeiL.setImageResource(R.mipmap.icon_home_warning)
                                            }
                                        }
                                    }

                                    1 -> {// 1-开启
                                        when (index) {
                                            1 -> {
                                                binding.homeClWenDuL1.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_fc7c7c
                                                    )
                                                binding.homeTvWenDuL1.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_fc7c7c
                                                    )
                                                )
                                            }

                                            2 -> {
                                                binding.homeClWenDuL2.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_fc7c7c
                                                    )
                                                binding.homeTvWenDuL2.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_fc7c7c
                                                    )
                                                )
                                            }

                                            3 -> {
                                                binding.homeClWenDuL3.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_fc7c7c
                                                    )
                                                binding.homeTvWenDuL3.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_fc7c7c
                                                    )
                                                )
                                            }

                                            4 -> {
                                                binding.homeIvShuiWeiL.setImageResource(R.mipmap.icon_shui_liu_fc7c7c)
                                            }
                                        }
                                    }
                                }
                            }

                            2 -> {  //2右边
                                //01/02/03/04/05【水温 手柄头温度 水流量 水位】
                                val index = HexDataParse.dataToUInt(listOf(hexData[1]))
                                //01-开启 00-关闭
                                val flag = HexDataParse.dataToUInt(listOf(hexData[2]))
                                when (flag) {
                                    0 -> {
                                        when (index) {
                                            1 -> {
                                                binding.homeClWenDuR1.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_00c1cd
                                                    )
                                                binding.homeTvWenDuR1.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_00C1CD
                                                    )
                                                )
                                            }

                                            2 -> {
                                                binding.homeClWenDuR2.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_00c1cd
                                                    )
                                                binding.homeTvWenDuR2.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_00C1CD
                                                    )
                                                )
                                            }

                                            3 -> {
                                                binding.homeClWenDuR3.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_00c1cd
                                                    )
                                                binding.homeTvWenDuR3.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_00C1CD
                                                    )
                                                )
                                            }

                                            4 -> {
                                                binding.homeIvShuiWeiR.setImageResource(R.mipmap.icon_home_warning)
                                            }
                                        }
                                    }

                                    1 -> {
                                        when (index) {
                                            1 -> {
                                                binding.homeClWenDuR1.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_fc7c7c
                                                    )
                                                binding.homeTvWenDuR1.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_fc7c7c
                                                    )
                                                )
                                            }

                                            2 -> {
                                                binding.homeClWenDuR2.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_fc7c7c
                                                    )
                                                binding.homeTvWenDuR2.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_fc7c7c
                                                    )
                                                )
                                            }

                                            3 -> {
                                                binding.homeClWenDuR3.background =
                                                    ContextCompat.getDrawable(
                                                        this, R.drawable.shape_circle_fc7c7c
                                                    )
                                                binding.homeTvWenDuR3.setTextColor(
                                                    ContextCompat.getColor(
                                                        this, R.color.color_fc7c7c
                                                    )
                                                )
                                            }

                                            4 -> {
                                                binding.homeIvShuiWeiR.setImageResource(R.mipmap.icon_shui_liu_fc7c7c)
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                KeyUtil.EB -> {   //指令11 （接收4个参数，使用在工作页面最底部数字显示）
                    if (hexData.size == 3) {
                        val fangXiang = HexDataParse.dataToUInt(listOf(hexData[0]))
                        when (fangXiang) {
                            1 -> {  //1左边 2右边
                                val index = HexDataParse.dataToUInt(listOf(hexData[1]))
                                val num = HexDataParse.hexByteToSignedInt(hexData[2])
                                runOnUiThread {
                                    when (index) {
                                        1 -> {
                                            binding.homeTvWenDuL1.setText(num.toString())
                                        }

                                        2 -> {
                                            binding.homeTvWenDuL2.setText(num.toString())
                                        }

                                        3 -> {
                                            binding.homeTvWenDuL3.setText(num.toString())
                                        }

                                        4 -> {}
                                    }
                                }
                            }

                            2 -> {  //1左边 2右边
                                val index = HexDataParse.dataToUInt(listOf(hexData[1]))
                                val num = HexDataParse.hexByteToSignedInt(hexData[2])
                                runOnUiThread {
                                    when (index) {
                                        1 -> {
                                            binding.homeTvWenDuR1.setText(num.toString())
                                        }

                                        2 -> {
                                            binding.homeTvWenDuR2.setText(num.toString())
                                        }

                                        3 -> {
                                            binding.homeTvWenDuR3.setText(num.toString())
                                        }

                                        4 -> {}
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        initClick()
        BluetoothSocketManager.addDataReceivedListener(dataListener)
    }

    private fun initClick() {
        binding.homeIvBack.setOnClickListener { finish() }

        binding.homeSetting.setOnClickListener {
            val intent = Intent(this, MineActivity::class.java)
            startActivity(intent)
        }

        initJianL()
        initJiaL()

        initJianR()
        initJiaR()
        checkJiaJianClickDrable()

        //跳转用户列表MineActivity
        binding.homeIvAvatarL.setOnClickListener {
            LiveEventBus.get<Boolean>(KeyUtil.HOME_SELECT_USER).post(true)
            startActivity(Intent(this, MineActivity::class.java))
        }
        //跳转用户列表MineActivity
        binding.homeIvAvatarR.setOnClickListener {
            LiveEventBus.get<Boolean>(KeyUtil.HOME_SELECT_USER).post(false)
            startActivity(Intent(this, MineActivity::class.java))
        }

        //保存L
        binding.homeLlSaveL.setOnClickListener {
            if (leftUserModel == null) {
                ToastUtils.showCenter(getString(R.string.no_user_select))
                return@setOnClickListener
            }
            val l1Result = binding.homeSeekBar1l.getProgress()
            val l2Result = binding.homeSeekBar2l.getProgress()
            val l3Result = binding.homeSeekBar3l.getProgress()

            SPUtil.put(KeyUtil.HOME_SEEKBAR_1_L, l1Result)
            SPUtil.put(KeyUtil.HOME_SEEKBAR_2_L, l2Result)
            SPUtil.put(KeyUtil.HOME_SEEKBAR_3_L, l3Result)
            CoreUtil.showIvCustomToast(
                binding.homeIvSaveL, R.mipmap.icon_save_success_00c1cd, R.mipmap.icon_alarm_save
            )

            val leftData1 = binding.homeSeekBar1l.getProgress()
            val leftData2 = binding.homeSeekBar2l.getProgress()
            val leftData3 = binding.homeSeekBar3l.getProgress()

            leftUserModel?.let {
                it.intensityValue = leftData1
                it.durationValue = leftData2
                it.FrequencyValue = leftData3
                UserRepository.updateUser(it)
            }
            Log.i(TAG, "保存-- ${Gson().toJson(leftUserModel)}")
        }

        //保存R
        binding.homeLlSaveR.setOnClickListener {
            if (rightUserModel == null) {
                ToastUtils.showCenter(getString(R.string.no_user_select))
                return@setOnClickListener
            }
            val r1Result = binding.homeSeekBar1R.getProgress()
            val r2Result = binding.homeSeekBar2R.getProgress()
            val r3Result = binding.homeSeekBar3R.getProgress()

            SPUtil.put(KeyUtil.HOME_SEEKBAR_1_R, r1Result)
            SPUtil.put(KeyUtil.HOME_SEEKBAR_2_R, r2Result)
            SPUtil.put(KeyUtil.HOME_SEEKBAR_3_R, r3Result)
            CoreUtil.showIvCustomToast(
                binding.ivSaveR, R.mipmap.icon_save_success_00c1cd, R.mipmap.icon_alarm_save
            )
            val rightData1 = binding.homeSeekBar1R.getProgress()
            val rightData2 = binding.homeSeekBar2R.getProgress()
            val rightData3 = binding.homeSeekBar3R.getProgress()

            rightUserModel?.let {
                it.intensityValue = rightData1
                it.durationValue = rightData2
                it.FrequencyValue = rightData3
                UserRepository.updateUser(it)
            }
            Log.i(TAG, "保存-- ${Gson().toJson(leftUserModel)}")
        }

        //开始按钮L
        binding.homeClActionL.setOnClickListener {
            when (actionFlagL) {
                0 -> {
                    binding.homeIvActionL.setImageResource(R.mipmap.icon_pause)
                    actionFlagL = 1
                }

                1 -> {
                    binding.homeIvActionL.setImageResource(R.mipmap.icon_home_pause)
                    actionFlagL = 0
                }
            }
            sendActionFlag("L", actionFlagL)
        }
        //开始按钮R
        binding.homeClActionR.setOnClickListener {
            when (actionFlagR) {
                0 -> {
                    binding.homeIvActionR.setImageResource(R.mipmap.icon_pause)
                    actionFlagR = 1
                }

                1 -> {
                    binding.homeIvActionR.setImageResource(R.mipmap.icon_home_pause)
                    actionFlagR = 0
                }
            }
            sendActionFlag("R", actionFlagR)
        }

        LiveEventBus.get<Map<Int, SelectModel>>(KeyUtil.TO_HOME_ACTIVITY)
            .observeSticky(this, { it ->
                it[0]?.let { lResult ->
                    when (lResult.model1) {
                        "tuo_mao" -> {
                            when (lResult.model2) {
                                //专家模式下不显示性别、部位、和肤色
                                getString(R.string.expert_mode_low) -> {
                                    binding.homeClSexL.visibility = View.GONE
                                    binding.homeClSexR.visibility = View.GONE

                                    binding.homeTvLocationL.visibility = View.GONE
                                    binding.homeTvLocationR.visibility = View.GONE
                                    binding.homeClColorL.visibility = View.GONE
                                    binding.homeClColorR.visibility = View.GONE
                                }

                                else -> {
                                    when (lResult.sex) {
                                        0 -> { //女士
                                            binding.homeTvSexL.text = getString(R.string.female)
                                        }

                                        1 -> { //男士
                                            binding.homeTvSexL.text = getString(R.string.male)
                                        }
                                    }

                                    when (lResult.color) {
                                        0 -> {
                                            binding.homeIvColorL.setImageResource(R.mipmap.icon_type1)
                                            binding.homeTvColorL.text = getString(R.string.Type_I)
                                        }

                                        1 -> {
                                            binding.homeTvColorL.text = getString(R.string.Type_II)
                                            binding.homeIvColorL.setImageResource(R.mipmap.icon_type2)
                                        }

                                        2 -> {
                                            binding.homeTvColorL.text = getString(R.string.Type_III)
                                            binding.homeIvColorL.setImageResource(R.mipmap.icon_type3)
                                        }

                                        3 -> {
                                            binding.homeTvColorL.text = getString(R.string.Type_IV)
                                            binding.homeIvColorL.setImageResource(R.mipmap.icon_type4)
                                        }

                                        4 -> {
                                            binding.homeTvColorL.text = getString(R.string.Type_V)
                                            binding.homeIvColorL.setImageResource(R.mipmap.icon_type5)
                                        }

                                        5 -> {
                                            binding.homeTvColorL.text = getString(R.string.Type_VI)
                                            binding.homeIvColorL.setImageResource(R.mipmap.icon_type6)
                                        }
                                    }
                                    when (lResult.location) {
                                        0 -> {
                                            binding.homeTvLocationL.text = getString(R.string.face)
                                        }

                                        1 -> {
                                            binding.homeTvLocationL.text =
                                                getString(R.string.Underarms)
                                        }

                                        2 -> {
                                            binding.homeTvLocationL.text = getString(R.string.Arms)
                                        }

                                        3 -> {
                                            binding.homeTvLocationL.text =
                                                getString(R.string.Abdomen)
                                        }

                                        4 -> {
                                            binding.homeTvLocationL.text =
                                                getString(R.string.Bikini)
                                        }

                                        5 -> {
                                            binding.homeTvLocationL.text = getString(R.string.Legs)
                                        }
                                    }
                                }
                            }
                            binding.homeTvModel2L.text = lResult.model2
                            binding.homeTvModel2R.text = lResult.model2
                        }

                        "nen_fu" -> {
                            when (lResult.location) {
                                0 -> {
                                    binding.homeTvLocationL.text = getString(R.string.face)
                                }

                                1 -> {
                                    binding.homeTvLocationL.text = getString(R.string.Underarms)
                                }

                                2 -> {
                                    binding.homeTvLocationL.text = getString(R.string.Arms)
                                }

                                3 -> {
                                    binding.homeTvLocationL.text = getString(R.string.Abdomen)
                                }

                                4 -> {
                                    binding.homeTvLocationL.text = getString(R.string.Bikini)
                                }

                                5 -> {
                                    binding.homeTvLocationL.text = getString(R.string.Legs)
                                }
                            }

                            binding.homeTvModel2L.visibility = View.GONE
                            binding.homeClColorL.visibility = View.GONE
                            binding.homeTvModel2R.visibility = View.GONE
                            binding.homeClColorR.visibility = View.GONE
                        }
                    }
                }
                it[1]?.let { rResult ->
                    when (rResult.model1) {
                        "tuo_mao" -> {
                            when (rResult.sex) {
                                0 -> { //女士
                                    binding.homeTvSexR.text = getString(R.string.female)
                                }

                                1 -> { //男士
                                    binding.homeTvSexR.text = getString(R.string.male)
                                }
                            }

                            when (rResult.color) {
                                0 -> {
                                    binding.homeIvColorR.setImageResource(R.mipmap.icon_type1)
                                    binding.homeTvColorR.text = getString(R.string.Type_I)
                                }

                                1 -> {
                                    binding.homeTvColorR.text = getString(R.string.Type_II)
                                    binding.homeIvColorR.setImageResource(R.mipmap.icon_type2)
                                }

                                2 -> {
                                    binding.homeTvColorR.text = getString(R.string.Type_III)
                                    binding.homeIvColorR.setImageResource(R.mipmap.icon_type3)
                                }

                                3 -> {
                                    binding.homeTvColorR.text = getString(R.string.Type_IV)
                                    binding.homeIvColorR.setImageResource(R.mipmap.icon_type4)
                                }

                                4 -> {
                                    binding.homeTvColorR.text = getString(R.string.Type_V)
                                    binding.homeIvColorR.setImageResource(R.mipmap.icon_type5)
                                }

                                5 -> {
                                    binding.homeTvColorR.text = getString(R.string.Type_VI)
                                    binding.homeIvColorR.setImageResource(R.mipmap.icon_type6)
                                }
                            }

                            when (rResult.location) {
                                0 -> {
                                    binding.homeTvLocationR.text = getString(R.string.face)
                                }

                                1 -> {
                                    binding.homeTvLocationR.text = getString(R.string.Underarms)
                                }

                                2 -> {
                                    binding.homeTvLocationR.text = getString(R.string.Abdomen)
                                }

                                3 -> {
                                    binding.homeTvLocationR.text = getString(R.string.Bikini)
                                }

                                4 -> {
                                    binding.homeTvLocationR.text = getString(R.string.Arms)
                                }

                                5 -> {
                                    binding.homeTvLocationR.text = getString(R.string.Legs)
                                }
                            }

                            binding.homeTvModel2R.text = rResult.model2
                        }

                        "nen_fu" -> {
                            when (rResult.location) {
                                0 -> {
                                    binding.homeTvLocationR.text = getString(R.string.face)
                                }

                                1 -> {
                                    binding.homeTvLocationR.text = getString(R.string.Underarms)
                                }

                                2 -> {
                                    binding.homeTvLocationR.text = getString(R.string.Abdomen)
                                }

                                3 -> {
                                    binding.homeTvLocationR.text = getString(R.string.Bikini)
                                }

                                4 -> {
                                    binding.homeTvLocationR.text = getString(R.string.Arms)
                                }

                                5 -> {
                                    binding.homeTvLocationR.text = getString(R.string.Legs)
                                }
                            }
                            binding.homeTvModel2L.visibility = View.GONE
                            binding.homeClColorL.visibility = View.GONE
                            binding.homeTvModel2R.visibility = View.GONE
                            binding.homeClColorR.visibility = View.GONE
                        }
                    }
                }
            })

        //接收用户列表返回的数据
        LiveEventBus.get<Map<Boolean, UserModel>>(KeyUtil.HOME_SELECT_USER_VALUE)
            .observeSticky(this, { map ->
                if (map != null) {
                    map[true]?.let {    //左侧手柄用户
                        leftUserModel = it
                        binding.homeTvSexL.text = it.gender
                        binding.homeTvNameL.text = it.name
                        binding.homeTvPhoneL.text = it.phone
                        if (it.intensityValue != null && it.intensityValue!! > 0) {
                            setSeekBarValue1L(it.intensityValue!!)
                        }
                        if (it.durationValue != null && it.durationValue!! > 0) {
                            setSeekBarValue2L(it.durationValue!!)
                        }

                        if (it.FrequencyValue != null && it.FrequencyValue!! > 0) {
                            setSeekBarValue3L(it.FrequencyValue!!)
                        }

                        if (it.intensityValue != null && it.durationValue != null && it.FrequencyValue != null) {
                            sendUserValue(
                                "L", it.intensityValue!!, it.durationValue!!, it.FrequencyValue!!
                            )
                        }
                    }

                    map[false]?.let {    //右侧手柄用户
                        rightUserModel = it
                        binding.homeTvSexR.text = it.gender
                        binding.homeTvNameR.text = it.name
                        binding.homeTvPhoneR.text = it.phone
                        if (it.intensityValue != null && it.intensityValue!! > 0) {
                            setSeekBarValue1R(it.intensityValue!!)
                        }
                        if (it.durationValue != null && it.durationValue!! > 0) {
                            setSeekBarValue2R(it.durationValue!!)
                        }

                        if (it.FrequencyValue != null && it.FrequencyValue!! > 0) {
                            setSeekBarValue3R(it.FrequencyValue!!)
                        }
                        if (it.intensityValue != null && it.durationValue != null && it.FrequencyValue != null) {
                            sendUserValue(
                                "R", it.intensityValue!!, it.durationValue!!, it.FrequencyValue!!
                            )
                        }
                    }
                }
            })

        binding.homeSeekBar1l.setOnProgressChangeListener(object :
            HalfCircleSeekBar.OnProgressChangeListener {
            override fun onProgressChanged(progress: Int) {
                binding.homeTv1l.text = String.format(Locale.getDefault(), "%d", progress)
            }
        })

        binding.homeSeekBar2l.setOnProgressChangeListener(object :
            HalfCircleSeekBar.OnProgressChangeListener {
            override fun onProgressChanged(progress: Int) {
                binding.homeTv2l.text = String.format(Locale.getDefault(), "%d", progress)
            }
        })

        binding.homeSeekBar3l.setOnProgressChangeListener(object :
            HalfCircleSeekBar.OnProgressChangeListener {
            override fun onProgressChanged(progress: Int) {
                binding.homeTv3l.text = String.format(Locale.getDefault(), "%d", progress)
            }
        })

        binding.homeSeekBar1R.setOnProgressChangeListener(object :
            HalfCircleSeekBar.OnProgressChangeListener {
            override fun onProgressChanged(progress: Int) {
                binding.homeTv1R.text = String.format(Locale.getDefault(), "%d", progress)
            }
        })

        binding.homeSeekBar2R.setOnProgressChangeListener(object :
            HalfCircleSeekBar.OnProgressChangeListener {
            override fun onProgressChanged(progress: Int) {
                binding.homeTv2R.text = String.format(Locale.getDefault(), "%d", progress)
            }
        })

        binding.homeSeekBar3R.setOnProgressChangeListener(object :
            HalfCircleSeekBar.OnProgressChangeListener {
            override fun onProgressChanged(progress: Int) {
                binding.homeTv3R.text = String.format(Locale.getDefault(), "%d", progress)
            }
        })
    }

    private fun setSeekBarValue1L(value1: Int) {
        binding.homeSeekBar1l.setProgress(value1)
        binding.homeTv1l.setText(value1.toString())
    }

    private fun setSeekBarValue2L(value2: Int) {
        binding.homeSeekBar2l.setProgress(value2)
        binding.homeTv2l.setText(value2.toString())
    }

    private fun setSeekBarValue3L(value3: Int) {
        binding.homeSeekBar3l.setProgress(value3)
        binding.homeTv3l.setText(value3.toString())
    }

    private fun setSeekBarValue1R(value1: Int) {
        binding.homeSeekBar1R.setProgress(value1)
        binding.homeTv1R.setText(value1.toString())
    }

    private fun setSeekBarValue2R(value2: Int) {
        binding.homeSeekBar2R.setProgress(value2)
        binding.homeTv1R.setText(value2.toString())
    }

    private fun setSeekBarValue3R(value3: Int) {
        binding.homeSeekBar3R.setProgress(value3)
        binding.homeTv3R.setText(value3.toString())
    }

    //加加
    private fun initJiaR() {
        bindSimpleStepButton(
            "R", 21, binding.homeClJia1R, binding.homeSeekBar1R, binding.homeTv1R,
            true, max = seekBarMax1R, min = seekBarMin1R
        )
        bindSimpleStepButton(
            "R", 22, binding.homeClJia2R, binding.homeSeekBar2R, binding.homeTv2R,
            true, max = seekBarMax2R, min = seekBarMin2R
        )
        bindSimpleStepButton(
            "R", 23, binding.homeClJia3R, binding.homeSeekBar3R, binding.homeTv3R,
            true, max = seekBarMax3R, min = seekBarMin3R
        )
    }

    private fun initJianR() {
        binding.homeClJian1R.setOnClickListener {
            bindSimpleStepButton(
                "R", 11, binding.homeClJian1R, binding.homeSeekBar1R, binding.homeTv1R,
                false, max = seekBarMax1R, min = seekBarMin1R
            )
        }
        binding.homeClJian2R.setOnClickListener {
            bindSimpleStepButton(
                "R", 12, binding.homeClJian2R, binding.homeSeekBar2R, binding.homeTv2R,
                false, max = seekBarMax2R, min = seekBarMin2R
            )
        }
        binding.homeClJian3R.setOnClickListener {
            bindSimpleStepButton(
                "R", 13, binding.homeClJian3R, binding.homeSeekBar3R, binding.homeTv3R,
                false, max = seekBarMax3R, min = seekBarMin3R
            )
        }
    }

    //加加
    private fun initJiaL() {
        bindSimpleStepButton(
            "L", 21, binding.homeClJia1L, binding.homeSeekBar1l, binding.homeTv1l,
            true, max = seekBarMax1L, min = seekBarMin1L
        )
        bindSimpleStepButton(
            "L", 22, binding.homeClJia2L, binding.homeSeekBar2l, binding.homeTv2l,
            true, max = seekBarMax2L, min = seekBarMin2L
        )
        bindSimpleStepButton(
            "L", 23, binding.homeClJia3L, binding.homeSeekBar3l, binding.homeTv3l,
            true, max = seekBarMax3L, min = seekBarMin3L
        )
    }

    private fun initJianL() {
        bindSimpleStepButton(
            "L", 11, binding.homeClJian1L, binding.homeSeekBar1l, binding.homeTv1l,
            false, max = seekBarMax1L, min = seekBarMin1L
        )
        bindSimpleStepButton(
            "L", 12, binding.homeClJian2L, binding.homeSeekBar2l, binding.homeTv2l,
            false, max = seekBarMax1L, min = seekBarMin1L
        )
        bindSimpleStepButton(
            "L", 13, binding.homeClJian3L, binding.homeSeekBar3l, binding.homeTv3l,
            false, max = seekBarMax1L, min = seekBarMin1L
        )
    }

    //点击加减的按钮有个动效
    private fun checkJiaJianClickDrable() {
        setTouchFeedback(binding.homeClJian1L)
        setTouchFeedback(binding.homeClJian2L)
        setTouchFeedback(binding.homeClJian3L)
        setTouchFeedback(binding.homeClJian1R)
        setTouchFeedback(binding.homeClJian2R)
        setTouchFeedback(binding.homeClJian3R)

        setTouchFeedback(binding.homeClJia1L)
        setTouchFeedback(binding.homeClJia2L)
        setTouchFeedback(binding.homeClJia3L)
        setTouchFeedback(binding.homeClJia1R)
        setTouchFeedback(binding.homeClJia2R)
        setTouchFeedback(binding.homeClJia3R)
    }

    private fun setTouchFeedback(touchTarget: View) {
        touchTarget.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    touchTarget.setBackgroundResource(R.drawable.button_click)
                }

                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    touchTarget.setBackgroundResource(R.drawable.shape_circle_00c1cd)
                }
            }
            false
        }
    }

    private fun bindSimpleStepButton(
        fangxiang: String, index: Int, button: View, seekBar: HalfCircleSeekBar, textView: TextView,
        isIncrement: Boolean, step: Int = 1, min: Int, max: Int
    ) {
        button.setOnClickListener {
            var buttonCommand = ""
            when (fangxiang) {
                "L" -> {
                    when (index) {
                        11 -> {
                            buttonCommand = "01 " + "01 " + "01"
                        }

                        12 -> {
                            buttonCommand = "01 " + "02 " + "01"
                        }

                        13 -> {
                            buttonCommand = "01 " + "03 " + "01"
                        }

                        21 -> {
                            buttonCommand = "01 " + "01 " + "02"
                        }

                        22 -> {
                            buttonCommand = "01 " + "02 " + "02"
                        }

                        23 -> {
                            buttonCommand = "01 " + "03 " + "02"
                        }
                    }
                }

                "R" -> {
                    when (index) {
                        11 -> {
                            buttonCommand = "02 " + "01 " + "01"
                        }

                        12 -> {
                            buttonCommand = "02 " + "02 " + "01"
                        }

                        13 -> {
                            buttonCommand = "02 " + "03 " + "01"
                        }

                        21 -> {
                            buttonCommand = "02 " + "01 " + "02"
                        }

                        22 -> {
                            buttonCommand = "02 " + "02 " + "02"
                        }

                        23 -> {
                            buttonCommand = "02 " + "03 " + "02"
                        }
                    }
                }
            }
            /*val current = seekBar.getProgress()
            val newVal = when {
                isIncrement -> (current + step).coerceAtMost(max)
                else -> (current - step).coerceAtLeast(min)
            }
            seekBar.setProgress(newVal)
            textView.text = newVal.toString()*/

            val buttonCommandAll = KeyUtil.HOME_BUTTON_CLICK_COMMAND + buttonCommand + KeyUtil.EE
            val data = HexConverter.hexStringToByteArray(buttonCommandAll)
            Log.i(TAG, "加减的命令-- $buttonCommandAll")
            BluetoothSocketManager.send(data)
        }
    }

    private fun sendUserValue(fangXiang: String, value1: Int, value2: Int, value3: Int) {
        var mFangXiang = ""
        when (fangXiang) {
            "L" -> {
                mFangXiang = "01 "
            }

            "R" -> {
                mFangXiang = "02 "
            }
        }
        if (mFangXiang.isEmpty()) {
            return
        }
        val data1 = HexConverter.intTo2ByteHex(value1)
        val value1Hex = data1.joinToString(" ") { "%02X".format(it) }

        val data2 = HexConverter.intTo2ByteHex(value2)
        val value2Hex = data2.joinToString(" ") { "%02X".format(it) }

        val data3 = HexConverter.intTo1ByteHex(value3)
        val value3Hex = data3.joinToString(" ") { "%02X".format(it) }

        val commandAll =
            KeyUtil.USER_ITEM_VALUE_COMMAND + mFangXiang + value1Hex + " " + value2Hex + " " + value3Hex + KeyUtil.EE
        val data = HexConverter.hexStringToByteArray(commandAll)
        Log.i(TAG, "用户数据-- $commandAll")
        BluetoothSocketManager.send(data)
    }

    /**
     * 待机/准备
     * @param flag 1-待机 , 2-准备
     */
    private fun sendActionFlag(fangXiang: String, flag: Int) {
        var mFangXiang = ""
        when (fangXiang) {
            "L" -> {
                mFangXiang = "01 "
            }

            "R" -> {
                mFangXiang = "02 "
            }
        }
        var mFlag = when (flag) {
            0 -> "1 "
            1 -> "2 "
            else -> "0 "
        }

        val commandAll =
            KeyUtil.HOME_ACTION_FLAG + mFangXiang + "0" + mFlag + KeyUtil.EE
        Log.i(TAG, "启动还是准备--: $commandAll")
        val data = HexConverter.hexStringToByteArray(commandAll)
        BluetoothSocketManager.send(data)
    }

    /**
     * @param temp 1/2/3(待机/准备/输出)
     */
    private fun setupPlayButton(
        container: ConstraintLayout, iconView: AppCompatImageView, temp: Int, fangXiang: String
    ) {
        // 确保背景是 GradientDrawable（圆形）
        val backgroundDrawable = container.background
        if (backgroundDrawable !is GradientDrawable) {
            val circleDrawable = GradientDrawable()
            circleDrawable.shape = GradientDrawable.OVAL
            circleDrawable.setColor(ContextCompat.getColor(container.context, R.color.color_00C1CD))
            container.background = circleDrawable
        }

        // 如果有旧动画，先停止
        breathingAnimators[container]?.let { animator ->
            animator.cancel()
            breathingAnimators.remove(container)
        }

        when (temp) {
            1 -> { // 待机
                (container.background as? GradientDrawable)?.setColor(
                    ContextCompat.getColor(container.context, R.color.color_00C1CD)
                ) ?: run {
                    container.setBackgroundResource(R.drawable.shape_circle_00c1cd_shi)
                }
                iconView.setImageResource(R.mipmap.icon_home_pause)

                //待机状态下就暂停计时
                onPauseCommand(fangXiang)
            }

            2 -> { // 准备
                (container.background as? GradientDrawable)?.setColor(
                    ContextCompat.getColor(container.context, R.color.color_00C1CD)
                ) ?: run {
                    container.setBackgroundResource(R.drawable.shape_circle_00c1cd_shi)
                }
                iconView.setImageResource(R.mipmap.icon_pause)

                when (fangXiang) {
                    "L" -> {
                        if (receiveFlagL == 3) {    //上次是输出状态
                            //发送指令
                            sendCountIndex(mWorkCountL, "L")
                            //更新日期和次数
                            leftUserModel?.let {
                                it.treatmentDate = CoreUtil.getCurrentDateWithSimpleDateFormat()
                                //次数
                                val currentIndex =
                                    if (it.treatmentTimes == null) 0 else it.treatmentTimes
                                it.treatmentTimes = currentIndex!! + 1
                                UserRepository.updateUser(it)
                            }
                        }
                    }

                    "R" -> {
                        if (receiveFlagR == 3) {    //上次是输出状态
                            //发送指令
                            sendCountIndex(mWorkCountR, "R")
                            //更新日期和次数
                            rightUserModel?.let {
                                it.treatmentDate = CoreUtil.getCurrentDateWithSimpleDateFormat()
                                //次数
                                val currentIndex =
                                    if (it.treatmentTimes == null) 0 else it.treatmentTimes
                                it.treatmentTimes = currentIndex!! + 1
                                UserRepository.updateUser(it)
                            }
                        }
                    }
                }
                //准备状态下开始发送计时命令
                onStartCommand(fangXiang)
            }

            3 -> { // 输出 -> 开启呼吸动画
                val breathingAnimator = ValueAnimator.ofArgb(
                    ContextCompat.getColor(container.context, R.color.color_00C1CD),
                    Color.parseColor("#88fc7c7c")
                ).apply {
                    duration = 1000L
                    repeatCount = ValueAnimator.INFINITE
                    repeatMode = ValueAnimator.REVERSE
                    addUpdateListener { animator ->
                        val color = animator.animatedValue as Int
                        (container.background as GradientDrawable).setColor(color)
                    }
                    start()
                }
                breathingAnimators[container] = breathingAnimator
                iconView.setImageResource(R.mipmap.icon_pause)
            }
        }
    }

    //设置当前的值（点击加减按钮后有后台返回的数值显示上去）
    private fun setSeekbarValue(
        seekBarProgress: HalfCircleSeekBar, textView: AppCompatTextView, value: Int
    ) {
        runOnUiThread {
            seekBarProgress.setProgress(value)
            textView.setText(value.toString())
        }
    }

    /*private fun setupPlayButton() {
        // 确保背景是 GradientDrawable（圆形）
        val backgroundDrawable = binding.homeClActionL.background
        if (backgroundDrawable !is GradientDrawable) {
            // 如果不是，尝试设置一个默认圆形背景
            val circleDrawable = GradientDrawable()
            circleDrawable.shape = GradientDrawable.OVAL
            circleDrawable.setColor(getColor(R.color.color_00C1CD)) // 初始颜色
            binding.homeClActionL.background = circleDrawable
        }

        breathingAnimator = ValueAnimator.ofArgb(
            Color.parseColor("#00C1CD"),       // 颜色1：原始色
            Color.parseColor("#88E0F0F0")      // 颜色2：浅色呼吸效果
        ).apply {
            duration = 1000L
            repeatCount = ValueAnimator.INFINITE
            repeatMode = ValueAnimator.REVERSE
            addUpdateListener { animator ->
                val color = animator.animatedValue as Int
                (binding.homeClActionL.background as GradientDrawable).setColor(color)
            }
        }

        binding.homeClActionL.setOnClickListener {
            if (isPlayingL) {
                pauseAnimation()
            } else {
                startAnimation()
                sendActionFlag("L", 2)
            }
        }
    }

    private fun startAnimation() {
        isPlayingL = true
        breathingAnimator?.start()
        binding.homeIvActionL.setImageResource(R.mipmap.icon_pause) // 切换图标为暂停
    }

    private fun pauseAnimation() {
        isPlayingL = false
        breathingAnimator?.cancel()
        val backgroundDrawable = binding.homeClActionL.background
        if (backgroundDrawable is GradientDrawable) {
            backgroundDrawable.setColor(getColor(R.color.color_00C1CD))
        } else {
            // 如果不是 GradientDrawable，就重新设置成初始圆形背景
            binding.homeClActionL.setBackgroundResource(R.drawable.shape_circle_00c1cd_shi)
        }
        binding.homeIvActionL.setImageResource(R.mipmap.icon_home_pause) // 切换图标为播放
    }*/

    //倒计时开始
    private fun onStartCommand(key: String) {
        val controller = controllers[key]
        if (controller == null) {
            val newController = WorkTimerController(
                when (key) {
                    "L" -> binding.homeSeekBar3l.getProgress()
                    "R" -> binding.homeSeekBar3R.getProgress()
                    else -> {
                        0
                    }
                },
                when (key) {
                    "L" -> if (SPUtil.getInt(KeyUtil.HANDLE_SEND_COUNT_ALL_L) == null) 0
                    else SPUtil.getInt(KeyUtil.HANDLE_SEND_COUNT_ALL_L)!!

                    "R" -> if (SPUtil.getInt(KeyUtil.HANDLE_SEND_COUNT_ALL_R) == null) 0
                    else SPUtil.getInt(KeyUtil.HANDLE_SEND_COUNT_ALL_R)!!

                    else -> {
                        0
                    }
                },
                onSendCommand = { mCount -> //每到一分钟就发送一次
                    Log.i(TAG, "运行的次数-- " + mCount + " -方向：" + key)
                    //存储到本地，到设置页面时候可以显示过去
                    when (key) {
                        "L" -> {
                            mWorkCountL = mCount
                            SPUtil.put(KeyUtil.HANDLE_SEND_COUNT_ALL_L, mCount)
                        }

                        "R" -> {
                            mWorkCountR = mCount
                            SPUtil.put(KeyUtil.HANDLE_SEND_COUNT_ALL_R, mCount)
                        }
                    }
                },
                onFinish = {
//                    ImageDialogShow().showing(supportFragmentManager, key, 0)
                })
            controllers[key] = newController
            newController.start()
        } else {
            controller.start() // 已存在的，继续运行
        }
    }

    /**
     * 发送手柄累计的运行次数
     */
    private fun sendCountIndex(mCount: Int, key: String) {
        val hexCount = HexDataParse.intToFixed4ByteHex(mCount)
        val value = HexConverter.hexListToSpacedString(hexCount)
        val commandAll =
            KeyUtil.SEND_TIMER_COUNT_ALL + when (key) {
                "L" -> "01"
                "R" -> "02"
                else -> "00"
            } + " " + value + " " + KeyUtil.EE
        val data = HexConverter.hexStringToByteArray(commandAll)
        Log.i(TAG, "发送计时的指令--: $commandAll")
        BluetoothSocketManager.send(data)
    }

    //倒计时暂停
    private fun onPauseCommand(key: String) {
        controllers[key]?.pause()
    }

    override fun onDestroy() {
        super.onDestroy()
        // 避免内存泄漏或多次回调
        BluetoothSocketManager.removeDataReceivedListener(dataListener)
    }
}